
const voListD=[]
const myRemoveLayui = function (obj) {
    //加删除的id
    let item=$(obj).parent()
    voListD.push({
        teacherName: $(item).find("input[myid='one']").val(),
        teacherIntroduce: $(item).find("input[myid='two']").val(),
        teacherId: $(item).find("input[myid='three']").val(),
        isDelete:'12'
    })


    $(obj).parent().remove();
}
const addLayuiItems = () => {
    let str = `
						<div class="layui-form-item" style="display: flex;">
                            <div class="layui-inline" style="width: calc((100% - 20px) / 2);">
                                <label class="layui-form-label required">讲师姓名</label>
                                <div class="layui-input-block">
                                    <input class="form-control " myid="one" type="text" placeholder="请输入讲师姓名">
                                </div>
                            </div>
                            <div class="layui-inline" style="width: calc((100% - 20px) / 2);">
                                <label class="layui-form-label required">讲师简介</label>
                                <div class="layui-input-block">
                                     <textarea   placeholder="请输入讲师简介" lay-verify="introduction" 
                                              myid="two"
                                              class="layui-textarea"></textarea>
                                  <input value="" myid="three" style="display: none">  
                                </div>
                            </div>
                             
							<button  class="layui-inline layui-btn myremove1" type="button" onclick="myRemoveLayui(this)">删除</button>
                        </div>
	`
    $('#LayuiItems').append(str)
}


$("body").on('click', '.remove', function () {
    $(this).parents('.newSet').remove();
})

layui.use(['form', 'xmSelect', 'upload', 'laydate'], function () {
    var form = layui.form;
    var layer = layui.layer, laydate = layui.laydate;
    var xmSelect = layui.xmSelect, upload = layui.upload;
    var loading;
    let datas = [];

    form.on('switch(switchTest)', function (data) {
        $('#homeSort').prop('disabled', !this.checked);
    })



    form.on('radio(demo-radio-filter)', function (data) {

        if (data?.elem?.value == '1') {
            $('#refuseReason').show()
        } else {
            $('#refuseReason').hide()
            $("textarea[name='refuseReason']").val('');
        }

    });

    //同时绑定多个元素，并将属性设定在元素上
    upload.render({
        elem: '.uploadSend'
        , multiple: 'true'
        , accept: 'images '
        , acceptMime: 'image/*'
        , before: function () {
            loading = layer.load({
                type: 3,
                content: '加载中...',
            });//在post之前定义loading
        }
        , done: function (res) {
            layer.close(loading);
            if (res.code == 0) {
                let that = this;
                changBackfill(res, that);
            } else {
                layer.msg('上传失败,请检查');
            }

        }
        , error: function (res) {
            layer.msg(res.msg)
        }
    })

    if ($('#inputType').val() != 'info') {
        //自定义验证规则
        form.verify({
            name: function (value, item) {
                if (null==value||''==value) {
                    return '请输入课程名称';
                }
            },
            // sort: function (value, item) {
            //     if (null==value||''==value) {
            //         return '请输入课程优先级';
            //     }
            // },
            price: function (value, item) {
                if (null==value||''==value) {
                    return '请输入课程价格';
                }
            },
            introduce: function (value, item) {
                if (null==value||''==value) {
                    return '请输入课程简介';
                }
            },
        });
    }
    //提交事件
    form.on('submit(submit)', function (data) {
        let params = data.field
        if ($('#inputType').val() != 'info') {
            if ('' == params.introduce) {
                layer.msg('请在基础信息中输入课程简介')
                return false
            }
            if ('' == params.introduce) {
                layer.msg('请输入课程简介')
                return false
            }
            if ('' == params.imgUrl) {
                layer.msg('请在课程封面添加封面')
                return false
            }
            if ('' == params.detailImg) {
                layer.msg('请在课程图片添加封面')
                return false
            }

        }
        let mylayuiItems = $('#LayuiItems').find('.layui-form-item')
        let voList = []
        for (let i = 0; i < mylayuiItems.length; i++) {
            let item = $(mylayuiItems[i])
            if ($('#inputType').val() != 'info') {
                if ('' == $(item).find("input[myid='one']").val()) {
                    layer.msg(`请在讲师信息中输入第${i + 1}个讲师姓名`)
                    return false
                }
                if ('' == $(item).find("textarea[myid='two']").val()) {
                    layer.msg(`请在讲师信息中输入第${i + 1}个讲师简介`)
                    return false
                }
            }
            voList.push({
                teacherName: $(item).find("input[myid='one']").val(),
                teacherIntroduce: $(item).find("textarea[myid='two']").val(),
                teacherId: $(item).find("input[myid='three']").val()

            })
        }
        if(voListD.length > 0 && $("#inputType").val() != 'add'){
            params.voList = [...voList,...voListD]
        }else{
            params.voList = [...voList]
        }


        if ($('#inputType').val() == 'add'||$('#inputType').val() == 'edit') {
            //装换
            params.isShow = params.isShow == 'no' ? 0 : 1
            if($('#inputType').val() == 'edit'){
                params.id=$('#userId').val()
            }
            AjaxPost($('#inputType').val() == 'add'?'/jzweb/jazCourses/saveCourse':'/jzweb/jazCourses/updateCourse', params).then(function (response) {
                parent.layer.msg("操作成功");
                var index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
                parent.layer.close(index);
                parent.load();
            }).catch(error => {
                layer.msg(error.msg)
            })
        } else if ($('#inputType').val() == 'info') {
            AjaxGet('/jzweb/jazGroupProd/checkGroup', {id:$('#userId').val(),state:params.checkStatus,result:params.checkStatus==0?'':params.checkResult}).then(function (response) {
                parent.layer.msg("操作成功");
                var index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
                parent.layer.close(index);
                parent.load();
            }).catch(error => {
                layer.msg(error.msg)
            })
        }

    });

});

let image = $("input[name='imgUrl']").val()==''?[]:$("input[name='imgUrl']").val().split(',')
let detailImg =$("input[name='detailImg']").val()==''?[]:$("input[name='detailImg']").val().split(',')
function changBackfill(res, obj) {
    if (obj.id == 'image') {
        if (image.length < obj.number) {
            image.push(res.data);
            $("#" + obj.id).prepend(`
					<div class="layui-inline mybutton" style="padding: 0">
						<img class="upImg" src="${res.data}" style="height: 100%;width: 100%">
						<img class="closeUpload" data-index="${image?.length - 1}" src="/img/close.png" data-id="image">
					</div>
					`)


            $("input[name='imgUrl']").val(image.join(','));
        } else {
            layer.msg('上传的图片已达上限，请删除在传')
        }
    }
    if (obj.id == 'detailImg') {
        if (detailImg.length < obj.number) {
            detailImg.push(res.data);
            $("#" + obj.id).prepend(`
					<div class="layui-inline mybutton" style="padding: 0">
						<img class="upImg" src="${res.data}" style="height: 100%;width: 100%">
						<img class="closeUpload" data-index="${detailImg?.length - 1}" src="/img/close.png" data-id="detailImg">
					</div>
					`)
            $("input[name='detailImg']").val(detailImg.join(','));
        } else {
            layer.msg('上传的图片已达上限，请删除在传')
        }
    }

    closeUpload()
}
closeUpload();
function closeUpload() {

    // 删除图片
    $(".closeUpload").unbind("click");
    $(".closeUpload").click(function () {

        $(this).parents('.layui-inline').remove();
        let objId = $(this).attr('data-id');
        console.log(objId)
        if (objId == 'image') {
            image.splice($(this).attr('data-index'), 1);
            $("input[name='imgUrl']").val(image.join(','));
        }
        if (objId == 'detailImg') {
            detailImg.splice($(this).attr('data-index'), 1);
            $("input[name='detailImg']").val(detailImg.join(','));
        }
    })

}
